package com.example.myapplication.picUtils

/**
 * @ProjectName: My Application
 * @Package: com.example.myapplication.picUtils
 * @ClassName: ImagePreviewActivity
 * @Description: 描述类的作用
 * @Author: xzw
 * @CreateDate: 2025/9/9 10:34
 * @UpdateUser: xzw：
 * @UpdateDate: 2025/9/9 10:34
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import coil.load
import com.example.myapplication.R

class ImagePreviewActivity : AppCompatActivity() {

    private lateinit var viewPager: ViewPager2
    private lateinit var previewAdapter: PreviewAdapter
    private lateinit var tvIndicator: TextView // 用于显示 "1/5" 这样的指示器
    private lateinit var cbSelectCurrent: CheckBox // 用于选择/取消选择当前图片
    private lateinit var btnDonePreview: Button // 完成按钮

    private var currentImages = mutableListOf<ImageItem>() // 从 ImagePickerActivity 传递过来的选中图片
    private var initiallySelectedImages = mutableListOf<ImageItem>() // 初始选中的图片，用于比较变化
    private var maxSelectionCount: Int = 9 // 从 ImagePickerActivity 传递过来

    private var currentPosition = 0

    companion object {
        const val EXTRA_IMAGES_TO_PREVIEW = "images_to_preview"
        const val EXTRA_INITIALLY_SELECTED_IMAGES = "initially_selected_images" // 可选，如果需要区分初始选择
        const val EXTRA_MAX_SELECTION_COUNT = "max_selection_count"
        const val EXTRA_CURRENT_POSITION = "current_position" // 点击预览时，当前图片在选中列表中的位置
        const val RESULT_UPDATED_SELECTED_IMAGES = "updated_selected_images"

        fun start(
            activity: Activity,
            requestCode: Int,
            imagesToPreview: ArrayList<ImageItem>, // 所有已选中的图片
            currentImagePosition: Int,
            maxCount: Int
        ) {
            val intent = Intent(activity, ImagePreviewActivity::class.java).apply {
                putParcelableArrayListExtra(EXTRA_IMAGES_TO_PREVIEW, imagesToPreview)
                putExtra(EXTRA_MAX_SELECTION_COUNT, maxCount)
                putExtra(EXTRA_CURRENT_POSITION, currentImagePosition)
            }
            activity.startActivityForResult(intent, requestCode)
        }
    }

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_preview) // 你需要创建这个布局文件

        viewPager = findViewById(R.id.view_pager_preview)
        tvIndicator = findViewById(R.id.tv_preview_indicator)
        cbSelectCurrent = findViewById(R.id.cb_preview_select_current)
        btnDonePreview = findViewById(R.id.btn_preview_done)

        intent.getParcelableArrayListExtra<ImageItem>(EXTRA_IMAGES_TO_PREVIEW)?.let {
            currentImages.addAll(it)
            initiallySelectedImages.addAll(it.map { item -> item.copy() }) // 创建副本用于比较
        }
        maxSelectionCount = intent.getIntExtra(EXTRA_MAX_SELECTION_COUNT, 9)
        currentPosition = intent.getIntExtra(EXTRA_CURRENT_POSITION, 0)


        if (currentImages.isEmpty()) {
            finish() // 如果没有图片，则关闭预览
            return
        }

        previewAdapter = PreviewAdapter(currentImages)
        viewPager.adapter = previewAdapter
        viewPager.setCurrentItem(currentPosition, false) // 跳转到指定预览的图片
        updateIndicator(currentPosition)
        updateCheckBoxState(currentPosition)
        updateDoneButtonState()

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentPosition = position
                updateIndicator(position)
                updateCheckBoxState(position)
            }
        })

        cbSelectCurrent.setOnClickListener {
            if (currentImages.isNotEmpty() && currentPosition < currentImages.size) {
                val currentImageItem = currentImages[currentPosition]
                val isChecked = cbSelectCurrent.isChecked

                if (isChecked) {
                    // 检查是否超过最大选择数 (理论上在 ImagePickerActivity 已控制，但预览时可以再次确认)
                    // 在预览中，我们主要是在“已选图片”的基础上进行“取消选择”
                    // 如果允许在预览中从未选中->选中，则需要数量检查
                    if (getSelectedCount() >= maxSelectionCount && !currentImageItem.isSelected) {
                        cbSelectCurrent.isChecked = false // 阻止选择
                        Toast.makeText(this, "最多选择 $maxSelectionCount 张图片", Toast.LENGTH_SHORT).show()
                        return@setOnClickListener
                    }
                    currentImageItem.isSelected = true
                } else {
                    currentImageItem.isSelected = false
                }
                updateDoneButtonState()
            }
        }

        btnDonePreview.setOnClickListener {
            returnResult()
        }

        // 处理返回按钮
        findViewById<ImageView>(R.id.iv_preview_back)?.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    private fun getSelectedCount(): Int {
        return currentImages.count { it.isSelected }
    }

    private fun updateIndicator(position: Int) {
        tvIndicator.text = "${position + 1}/${currentImages.size}"
    }

    private fun updateCheckBoxState(position: Int) {
        if (currentImages.isNotEmpty() && position < currentImages.size) {
            cbSelectCurrent.isChecked = currentImages[position].isSelected
        }
    }

    private fun updateDoneButtonState() {
        val selectedCount = getSelectedCount()
        if (selectedCount > 0) {
            btnDonePreview.text = "完成($selectedCount)"
            btnDonePreview.isEnabled = true
        } else {
            btnDonePreview.text = "完成"
            btnDonePreview.isEnabled = false // 如果不允许一张都不选，则可以调整这里的逻辑
        }
    }

    private fun returnResult() {
        val resultIntent = Intent()
        val finalSelectedImages = ArrayList(currentImages.filter { it.isSelected })
        resultIntent.putParcelableArrayListExtra(RESULT_UPDATED_SELECTED_IMAGES, finalSelectedImages)
        setResult(Activity.RESULT_OK, resultIntent)
        finish()
    }

    override fun onBackPressed() {
        returnResult() // 返回时也传递结果
        // super.onBackPressed() // 被上面的 finish() 替代
    }


}

// ViewPager2的Adapter
class PreviewAdapter(private val images: List<ImageItem>) :
    RecyclerView.Adapter<PreviewAdapter.PreviewViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PreviewViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_image_preview_fullscreen, parent, false) // 你需要创建这个item布局
        return PreviewViewHolder(view)
    }

    override fun onBindViewHolder(holder: PreviewViewHolder, position: Int) {
        holder.bind(images[position].uri)
    }

    override fun getItemCount(): Int = images.size

    class PreviewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val imageView: ImageView = itemView.findViewById(R.id.iv_fullscreen_image)

        fun bind(uri: Uri) {
            imageView.load(uri) {
                placeholder(R.drawable.ic_launcher_background) // 可选的占位图
                error(R.drawable.ic_launcher_background)         // 可选的错误图
            }
        }
    }
}
